package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(urlPatterns= {"/user/*","/admin/*"})
public class PermissionFilter implements Filter {
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		HttpSession session = httpServletRequest.getSession();
		Object o = session.getAttribute("role");
		String contextPath = httpServletRequest.getContextPath();
		if(o == null) {
			session.setAttribute("msg", "受保护资源，请先登录！");
			httpServletResponse.sendRedirect(contextPath + "/login.jsp");
			return;
		} 
		String role = (String)o;
		String requestURI = httpServletRequest.getRequestURI();
		if(requestURI.contains("/admin") && !"admin".equals(role)) {
			session.setAttribute("msg", "admin角色的受保护资源，请先登录！");
			httpServletResponse.sendRedirect(contextPath + "/login.jsp");
			return;
		}
		if(requestURI.contains("/user") && !"user".equals(role)) {
			session.setAttribute("msg", "user角色的受保护资源，请先登录！");
			httpServletResponse.sendRedirect(contextPath + "/login.jsp");
			return;
		}
		chain.doFilter(request, response);
	}
}